<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests\CategoryRequest;
use App\Http\Controllers\Controller;
use App\Model\Category;
use DB,Input,Validator;

/**
 * 商品分类控制器
 */
class FaqController extends Controller
{
    // 商品分类列表
    public function index(Request $request)
    {
        // 存储搜索条件
        $request->flashOnly('faq_title');
        
        $faqs = DB::table('faq')->where('faq_title', 'like', '%'. $request->get('faq_title') .'%')
                ->paginate(15);
        foreach($faqs as $faq){
            $faq->cate_name = DB::table('faq_category')->where('id', $faq->pid)->pluck('cate_name');
        }
        return view('admin.faq.index', compact('faqs'));
    }
    
    // 分类添加模板
    public function create($pid=0)
    {
        $cates = DB::table('faq_category')->lists('cate_name', 'id');
        
        return view('admin.faq.add', compact("cates",'pid'));
    }
    
    // 保存商品分类
    public function store(Request $request)
    {
        $input = $request->except('_token');
        $pid = $input['pid'];
        
        $result = DB::table('faq')->insert($input);
        
        if ($result) {
            return redirect('/admin/faq');
        } else {
            return back()->with(['errors'=>'添加失败']);
        }
    }
    
    // 修改分类
    public function edit($id)
    {
        $faq = DB::table('faq');
        $data = $faq->where('id', $id)->first();
        $cates = DB::table('faq_category')->lists('cate_name', 'id');
        return view('admin.faq.edit', compact("cates",'data'));
    }
    
    // 执行修改
    public function update(Request $request,$id)
    {
        $input = $request->except(['_token','_method']);
        $result = DB::table('faq')->where('id', $id)->update($input);
        if ($result) {
            return redirect('/admin/faq');
        } else {
            return back()->with(['errors'=>'修改失败']);
        }
    }
    
    public function show($id){
        
    }
    
    // 删除
    public function destroy($id)
    {
        $children = DB::table('faq')->where('id', $id)->first();
        $r = ['status'=>0, 'info'=>''];
        
        $res = DB::table('faq')->where('id', $id)->delete();

        if($res){
            $r['status'] = 1;
            $r['info'] = '删除成功';
        } else {
            $r['info'] = '删除失败';
        }
        return response()->json($r);
    }
}